package top.pmwly.filter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import top.pmwly.common.jwt.JwtToken;
import top.pmwly.common.utils.StringUtils;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Herther
 * @version 1.0.0
 * @ClassName JwtAuthencationTokenFilter.java
 * @Description jwt登录授权过滤器
 * @createTime 2021年09月21日 22:02:00
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Value("${jwt.header}")
    private String header;
    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Autowired
    private UserDetailsService userDetailsService;

    @Resource
    private JwtToken jwtToken;

    /**
     * 重写过滤器方法
     * @param request
     * @param response Authorization
     * @param chain
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        //从请求头中拿到token
        //Authorization
        String authHeader = request.getHeader(header);
        if (!StringUtils.isEmpty(authHeader) &&authHeader.startsWith(tokenHead)){
            //截取token
            String token = authHeader.substring(tokenHead.length());
            //token 中拿到username
            String username = jwtToken.getUsernameByToken(token);
            //token存在用户名但未登录
            if (!StringUtils.isEmpty(username)
                    && null == SecurityContextHolder.getContext().getAuthentication()){
                //登录
                UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                //验证token是否有效，重新设置用户对象
                if (jwtToken.vaildateTokne(token, userDetails)){
                    //构建username password  authentication
                    UsernamePasswordAuthenticationToken authenticationToken =
                            new UsernamePasswordAuthenticationToken
                                    (userDetails, null,userDetails.getAuthorities());
                    //重新设置对象
                    authenticationToken
                            .setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    //重新设置SpringSecurity全局对象
                    SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                }

            }
        }
        //放行
        chain.doFilter(request, response);

    }
}
